<script setup lang='ts' name="rights-management">
import type { VNode, VNodeProps } from 'vue'

import { assignRoles, delAdminRoles, getUserBySupplier, rIndexAdminRoles, rIndexPrivileges, updateAdminRoles } from '@fl/api/iam-api'
import { useUserStore } from '@fl/store/modules/user'
import { ElButton, ElCard, ElCheckbox, ElDialog, ElInput, ElTransfer, ElTree } from 'element-plus'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'

import type { Trees } from './types'

import roleCheckbox from './component/role-checkbox/index.vue'

const userStore = useUserStore()

const org_id = userStore.getUserInfo?.org_id
const roleCheckboxRef = ref<any>(null)
const treeRoleList = ref<any>([])
const authList = ref<any>([])
const role_id = ref<any>()
const roleInformation = ref<any>()
const roleInfoList = ref<any>([])
const dialogDistributionUserVisible = ref(false)
const assignRolesList = ref<any>([])
const resultList = ref<any>([])
const router = useRouter()
const alreadyHaveAuth = ref<any>([])
const rightValue = ref([])
const defaultProps = {
    children: 'children',
    label: 'label',
}

function handleNodeClick(data: any) {
    console.log(data)
    role_id.value = data.id
    treeRoleList.value.forEach((item: any) => {
        if (item.id === role_id.value)
            roleInformation.value = item
    })
    treeRoleList.value.forEach((item: any) => {
        if (data.id === item.id)
            alreadyHaveAuth.value = item.privileges
    })
    console.log(alreadyHaveAuth.value, 'alreadyHaveAuth.value')
    roleCheckboxRef.value.getAlreadyHaveAuth(alreadyHaveAuth.value)
}

getUserAuthList()
function getUserAuthList() {
    getUserBySupplier({
        Objectid: org_id,
    }).then((res) => {
        roleInfoList.value = res
        transferData.value = roleInfoList.value
    })
}

const dataTree = ref<any>([
    {
        children: [
            // {
            //     label: '所有员工',
            // },
            // {
            //     label: '所有管理员',
            // },
        ],
        label: '所有角色',
    },
])

const filterText = ref('')
const checkedAllPage = ref(false)

const isIndeterminate = ref(false)

const treeRef = ref<InstanceType<typeof ElTree>>()

function createSection() {
    router.push('/admin/authority/addRole')
}
function filterNode(value: string, data: Trees) {
    if (!value)
        return true
    return data.label.includes(value)
}

function handleCheckAll(val: boolean) {
    console.log(val, 'handleCheckAll')
    if (val)
        roleCheckboxRef.value.handleCheckAll(true)

    else
        roleCheckboxRef.value.handleCheckAll(false)
}
function distributionAuth() {
    console.log('保存')
    console.log(roleCheckboxRef.value.getCheckedCities, 'roleCheckboxRef.value')
    const options = {
        description: roleInformation.value.description,
        display_name: roleInformation.value.display_name,
        id: role_id.value,
        privileges: roleCheckboxRef.value.getCheckedCities,
    }
    console.log(options, roleInformation.value, 'optionsoptionsoptions')
    updateAdminRoles(options).then((res) => {
        console.log(res, 'distributionAuth')
    })
}
function renderFunc(h: (type: string, props: VNodeProps | null, children?: string) => VNode, option: any) {
    return h('span', null, option.name)
}
const transferData = ref<any>()

function handleChangeTransfer(value: number[] | string[], direction: 'left' | 'right', movedKeys: number[] | string[]) {
    console.log(value, direction, movedKeys, 'handleChangeTransfer')
    assignRolesList.value = value
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

function assignRolesConfirm() {
    const options = {
        // org_id: org_id,
        role_ids: [role_id.value],
        user_ids: assignRolesList.value,
    }
    console.log(options, 'optionsoptions')
    assignRoles(org_id, options).then((res) => {
        console.log(res, 'assignRolesConfirm')
        dialogDistributionUserVisible.value = false
    }).catch(() => {
        ElMessage({
            message: '操作失败',
            type: 'info',
        })
    })
}
function assignRolesClose() {
    dialogDistributionUserVisible.value = false
    rightValue.value = []
}
getDataTree()

async function getDataTree() {
    dataTree.value[0].children = []
    rIndexAdminRoles({
        org_id,
        page: 1,
        page_size: 9999,
    }).then((res: any) => {
        const target = res?.items ?? []
        treeRoleList.value = target
        if (target.length) {
            target.forEach((item) => {
                dataTree.value[0].children?.push({
                    id: item.id,
                    label: item.display_name,
                })
            })
        }
    })
}

getRIndexPrivileges()
async function getRIndexPrivileges() {
    rIndexPrivileges({ org_id }).then((res: any) => {
        authList.value = res
        resultList.value = Object.values(authList.value.reduce((acc, cur) => {
            const { module_name, ...rest } = cur
            if (acc[module_name])
                acc[module_name].children.push(rest)
            else
                acc[module_name] = { children: [rest], module_name }

            return acc
        }, {}))
        console.log(resultList.value, 'resultList.value')
    })
}

function removeTree(data: any) {
    ElMessageBox.confirm(
        '该操作将永久删除，是否继续?',
        '提示',
        {
            type: 'warning',
        },
    )
        .then(() => {
            delAdminRoles(data.id).then(() => {
                getDataTree()
            })
        })
        .catch(() => {})
}
function distributionUser(node: Node, data: any) {
    console.log(node, data, 'distributionUser')
    dialogDistributionUserVisible.value = true
}
</script>

<template>
    <div flex>
        <ElCard style="width:20%;height: 100vh;"
                mr-20
        >
            <div flex>
                <ElInput v-model="filterText" />

                <ElButton ml-6
                          class="el-button el-button--primary el-button--default"
                          @click="createSection"
                >
                    新增角色
                </ElButton>
            </div>

            <ElTree ref="treeRef"
                    style="max-width: 600px"
                    :data="dataTree"
                    :props="defaultProps"
                    node-key="id"
                    :filter-node-method="filterNode"
                    @node-click="handleNodeClick"
            >
                <template #default="{ node, data }">
                    <span class="custom-tree-node">
                        <span>{{ node.label }}</span>

                        <span v-if="node.label !== '所有角色'">
                            <Edit style="width: 1em; height: 1em; margin-left: 12px"
                                  @click="distributionUser(node, data)"
                            />

                            <Delete style="width: 1em; height: 1em; margin-left: 18px"
                                    @click="removeTree(data)"
                            />

                        </span>
                    </span>
                </template>
            </ElTree>
        </ElCard>

        <ElCard style="width:80%">
            <div style="align-items: center;"
                 mb-20
                 flex
                 justify-between
            >
                <span>设置[企业管理员]对应的应用功能权限</span>

                <div flex
                     style="align-items: center;"
                >
                    <ElCheckbox v-model="checkedAllPage"
                                label="全选"
                                :indeterminate="isIndeterminate"
                                @change="handleCheckAll"
                    />

                    <ElButton class="el-button el-button--primary el-button--default"
                              ml-20
                              @click="distributionAuth"
                    >
                        保存
                    </ElButton>
                </div>
            </div>

            <roleCheckbox v-if="resultList.length !== 0"
                          ref="roleCheckboxRef"
                          :result-list="resultList"
                          :already-have-auth="alreadyHaveAuth"
            />
        </ElCard>

        <ElDialog v-model="dialogDistributionUserVisible"
                  title="全部成员"
                  width="760"
        >
            <ElTransfer v-model="rightValue"
                        style="text-align: left; display: inline-block"
                        filterable
                        :left-default-checked="[2, 3]"
                        :right-default-checked="[1]"
                        :render-content="renderFunc"
                        :titles="['所有成员', '已选择人员']"
                        :button-texts="['', '']"
                        :format="{
                            noChecked: '${total}',
                            hasChecked: '${checked}/${total}',
                        }"
                        :props="{
                            key: 'code',
                            label: 'name',
                        }"
                        :data="transferData"
                        @change="handleChangeTransfer"
            />

            <template #footer>
                <div class="dialog-footer">
                    <ElButton @click="assignRolesClose">
                        取消
                    </ElButton>

                    <ElButton type="primary"
                              @click="assignRolesConfirm"
                    >
                        确认
                    </ElButton>
                </div>
            </template>
        </ElDialog>
    </div>
</template>

<style lang="scss" scoped>
:deep(.el-transfer-panel) {
    width: 260px;
}
</style>
